package org.wappumobileapp;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import com.thoughtworks.xstream.XStream;
import com.google.ads.*;

import android.content.res.Resources;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import dataobjects.Category;
import dataobjects.Message;
import android.text.format.DateFormat;

public class GetSuggestion extends BaseActivity implements ServerResponceListener{

	private Category selectedCategory;
	private TextView messageTextView;
	private TextView messageNickView;
	private TextView messageDateView;
	private TextView likeResultView;
	private TextView dontknowResultView;
	private TextView dislikeResultView;
	private Message currentMessage;
	
	private AdView adView;

	// Used to store the likes
	private List<Long> ids = new ArrayList<Long>();

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// just for debug now here, add jars from lib to build path and add
		// permission Internet, seems to work ok after that

		// TODO use the correct category user has selected
		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.get_suggestion);
		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,
				R.layout.windowtitle);
		
		// AD
		// Look up the AdView as a resource and load a request.
		adView = (AdView) this.findViewById(R.id.adView);
		adView.loadAd(new AdRequest());

		GetFromService.addServerResponceListener(this);
		// Save views that need to be updated
		messageTextView = (TextView) findViewById(R.id.SuggestionTextView);
		messageNickView = (TextView) findViewById(R.id.SuggestionNick);
		messageDateView = (TextView) findViewById(R.id.SuggestionDate);
		likeResultView = (TextView) findViewById(R.id.LikeResultTextView);
		dontknowResultView = (TextView) findViewById(R.id.DontknowResultTextView);
		dislikeResultView = (TextView) findViewById(R.id.DislikeResultTextView);

		// CategoryListActivity categorySelector = new CategoryListActivity();
		// didn't work. Would have been nice to reuse categoryList in smarter
		// way. :/

		// Initialize category list
		List<Category> categoryList = Arrays.asList(Category.values());
		/*
		 * categoryList.add(new Category(0, "ic_list")); categoryList.add(new
		 * Category(1, "ic_list")); categoryList.add(new Category(2,
		 * "ic_list2")); categoryList.add(new Category(3, "ic_list"));
		 * categoryList.add(new Category(4, "ic_list"));
		 */

		// Create a customized ArrayAdapter
		final CategoryArrayAdapter adapter = new CategoryArrayAdapter(
				getApplicationContext(), R.layout.category_listitem,
				categoryList);

		// Get reference to ListView holder
		final ListView lv = (ListView) this.findViewById(R.id.categoryListView);
		lv.setAdapter(adapter);

		// Select listeners
		lv.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
		lv.setClickable(true);
		lv.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				selectedCategory = adapter.setSelectable(position);
				// TODO!
				// Save different and move message to seen OR
				// just keep the current message in the list?
				refreshMessage();
			}
		});
		// Save current selected category.
		selectedCategory = adapter.getSelectedCategory();
		refreshMessage();

		// Buttons
		final Button likeButton = (Button) findViewById(R.id.like_button);
		likeButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				GetFromService.likeMessage(currentMessage);

				// Store the liked message locally
				
				refreshMessage();
			}
		});

		final Button dontknowButton = (Button) findViewById(R.id.dontknow_button);
		dontknowButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				GetFromService.indifferentMessage(currentMessage);
				refreshMessage();
			}
		});

		final Button dislikeButton = (Button) findViewById(R.id.dislike_button);
		dislikeButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				GetFromService.dislikeMessage(currentMessage);
				refreshMessage();
			}
		});
		final Button reportButton = (Button) findViewById(R.id.ReportButton); 
		reportButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				GetFromService.reportMessage(currentMessage);
				refreshMessage();
			}
		});;

	}

	/** Called before the activity is destroyed. */
	@Override
	public void onDestroy() {
		// Destroy the AdView.
		if (adView != null) {
			adView.destroy();
		}

		super.onDestroy();
	}
	
	public void refreshMessage() {
		Message m = GetFromService.readMessage(selectedCategory);
		if (m == null) {
			Resources res = getResources();
			messageTextView.setText(res
					.getString(R.string.category_no_messages));
			messageNickView.setText(res.getString(R.string.suggestion_nick));
			messageDateView.setText(res.getString(R.string.suggestion_date));
			likeResultView.setText("0");
			dontknowResultView.setText("0");
			dislikeResultView.setText("0");

		} else {
			currentMessage = m;
			messageTextView.setText(m.getMessage());
			messageNickView.setText(m.getNickname());
			messageDateView.setText(DateFormat.format("yyyy-MM-dd hh:mm:ss",
					m.getDate()));
			likeResultView.setText(m.getLikes().toString());
			dontknowResultView.setText(m.getIndifferent().toString());
			dislikeResultView.setText(m.getDislikes().toString());

		}

	}



	public void deleteSuccessful(Message m) {
		// TODO Auto-generated method stub
		
	}



	public void likeSuccessful(Message m) {
		XStream xstream = new XStream();
		File f = new File(
				"/data/data/org.wappumobileapp/files/my_likes.xml");
		if (f.exists()) {
			try {
				BufferedReader inputReader = new BufferedReader(
						new InputStreamReader(
								openFileInput("my_likes.xml")));
				ids = (List<Long>) xstream.fromXML(inputReader);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if(!ids.contains(currentMessage.getId())){
			ids.add(currentMessage.getId());
			writingHistory(ids, "my_likes.xml");
		}

	}



	public void dislikeSuccessful(Message m) {
		// TODO Auto-generated method stub
		
	}



	public void indifferentSuccesful(Message m) {
		// TODO Auto-generated method stub
		
	}



	public void handleError(String errormessage) {
		Toast.makeText(getApplicationContext(), R.string.NoConnection,
				Toast.LENGTH_LONG).show();
		
	}

}
